package com.cssy.yd.logic.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.logic.entity.LogicMaterialReturnItemBatchDO;
import com.cssy.yd.logic.entity.LogicMaterialReturnItemDO;
import com.cssy.yd.logic.entity.LogicOtherInwhDO;
import com.cssy.yd.logic.entity.LogicOtherInwhItemBatchDO;
import com.cssy.yd.logic.entity.LogicOtherInwhItemDO;
import com.cssy.yd.logic.entity.LogicWhmoveInwhItemDO;
import com.cssy.yd.logic.service.ILogicOtherInwhItemService;
import com.cssy.yd.logic.service.ILogicOtherInwhService;
import com.cssy.yd.logic.util.SqlUtil;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;

@Controller
@RequestMapping("/yd/logic/otherInwh")
public class LogicOtherInwhController extends BaseController<LogicOtherInwhDO>{

	private static final String MANAGER = "/yd/logic/otherinwh/Manager";
	private static final String EIDT = "/yd/logic/otherinwh/Operation";//添加、修改、显示页面
	private static final String ITEMMANAGER = "/yd/logic/otherinwh/ItemManager";//添加、修改、显示页面
	@Resource(name = "logicOtherInwhService")
	private ILogicOtherInwhService logicOtherInwhService;
	
	@Resource(name = "logicOtherInwhItemService")
	private ILogicOtherInwhItemService logicOtherInwhItemService;
	
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		return MANAGER;
	}

	@RequestMapping(value="itemManager")
	public String itemManager(HttpServletRequest request, Model model)
			throws Exception {
		String itemdata =request.getParameter("data");
		String billstatus =request.getParameter("billstatus");
		LogicOtherInwhItemDO lOtherInwhItemDO=JSONArray.parseObject(new String(itemdata.getBytes("ISO-8859-1"),"UTF-8"), LogicOtherInwhItemDO.class);
		LogicOtherInwhItemBatchDO inwhItemBatchDO = new LogicOtherInwhItemBatchDO();
		inwhItemBatchDO.setMaterialsid(lOtherInwhItemDO.getMaterialsid());
		inwhItemBatchDO.setOtherInwhItemId(lOtherInwhItemDO.getId());
		inwhItemBatchDO.setCode(lOtherInwhItemDO.getCode());
		inwhItemBatchDO.setName(lOtherInwhItemDO.getName());
		inwhItemBatchDO.setSpec(lOtherInwhItemDO.getSpec());
		inwhItemBatchDO.setJunit(lOtherInwhItemDO.getJunit());
		inwhItemBatchDO.setJquantity(lOtherInwhItemDO.getJquantity());
		inwhItemBatchDO.setUnit(lOtherInwhItemDO.getUnit());
		inwhItemBatchDO.setUnitconvert(lOtherInwhItemDO.getUnitconvert());
		inwhItemBatchDO.setQuantity(lOtherInwhItemDO.getQuantity());
		if(lOtherInwhItemDO.getItemBatch() != null & !"".equals(lOtherInwhItemDO.getItemBatch())){
			request.setAttribute("itemBatchDOs", lOtherInwhItemDO.getItemBatch());
		}
		request.setAttribute("billstatus", billstatus);
		request.setAttribute("inwhItemBatchDO", JSONArray.toJSONString(inwhItemBatchDO));
		return ITEMMANAGER;
	}
	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		 SearchConditions scs = new SearchConditions();
		 Map<String,Object> sqlMap = SqlUtil.sqlUtil.roleWhSqlFilter(request, scUserRolePlaceService,"wh_code");
		 scs.addCondition((String)sqlMap.get("option"), (List)sqlMap.get("roleWhList"));
		 hander.getWheres(scs);
			if(scs.getOrderBy()==null||"".equals(scs.getOrderBy()))
				 scs.setOrderBy("dctime desc");
		 SearchResult result= logicOtherInwhService.findListByExample(scs);
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);
		
	}
	@RequestMapping(value = "/itemlist")
	public void itemlist(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String itembatch =request.getParameter("itembatch");
		List<LogicOtherInwhItemBatchDO> itemBatchDOs=null;
		if(itembatch != null  && !"".equals(itembatch)){
			itemBatchDOs=JSONArray.parseArray(new String(itembatch.getBytes("ISO-8859-1"),"UTF-8"), LogicOtherInwhItemBatchDO.class);
		}
		SearchResult result= new SearchResult();
		if(itemBatchDOs != null && itemBatchDOs.size()>0){
			result.setRecordCount(itemBatchDOs.size());
			result.setResults(itemBatchDOs);
		}
		 OutJsonGrid out=new OutJsonGrid(result);
		 out.printJSon(response);
		
	}
	@Override
	public String operationForm(HttpServletRequest request,@PathVariable String id,
			@PathVariable  String flag, Model model) throws Exception {
		model.addAttribute("wh",SqlUtil.sqlUtil.roleWH(request, scUserRolePlaceService));
		if(OperationFlag.ADD.equals(flag)){//我新增加时操作
			model.addAttribute("viewflag", "add");
			model.addAttribute("xx", 1);//标示能不能修改内容
		}else{
			LogicOtherInwhDO oi = logicOtherInwhService.findListById(id);
			//List<LogicOtherInwhItemDO> loiilist = logicOtherInwhItemService.findByPid(id);
			if (oi.getBillStatus() == 1){
				model.addAttribute("xx", 1);//标示能不能修改内容
				model.addAttribute("viewflag", "tijiao");
			}else {
				model.addAttribute("xx", 2);//标示能不能修改内容
			}
			if (oi.getBillStatus() == 3){
				model.addAttribute("viewflag", "tongguo");
			}
			if (oi.getBillStatus() == 2){
				model.addAttribute("viewflag", "shenpi");
			}
			model.addAttribute("oi", oi);
			//model.addAttribute("axxJson", loiilist);
			
		}
		return EIDT;
	}

	@RequestMapping("/griditems")
	public void griditems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			List<LogicOtherInwhItemDO> loiilist = logicOtherInwhItemService.findByPid(id);
			OutJsonGrid out = new OutJsonGrid(loiilist);
			out.printJSon(response);
		}
	}
	
	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicOtherInwhDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata = request.getParameter("addressInfos");
		if(itemdata==null&&"".equals(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("物料不能为空！");
			return bodyMap.modelMap;
		}else{
				List<LogicOtherInwhItemDO> lInwhItemDOs  = JSONArray.parseArray(itemdata, LogicOtherInwhItemDO.class);
				for (LogicOtherInwhItemDO itemDO : lInwhItemDOs) {
					if("Y".equals(itemDO.getOpenBatch())){
						if("".equals(itemDO.getItemBatch()) || itemDO.getItemBatch()==null){
							bodyMap.isFail();
							bodyMap.configWebInfor("物料编码为:'"+itemDO.getCode()+"'没有分批次填写数据！");
							return bodyMap.modelMap;
						}else{
							List<LogicOtherInwhItemBatchDO> batchDOs  = JSONArray.parseArray(itemDO.getItemBatch(), LogicOtherInwhItemBatchDO.class);
							if(batchDOs==null || batchDOs.size() <= 0){
								bodyMap.isFail();
								bodyMap.configWebInfor("物料编码为:'"+itemDO.getCode()+"'没有分批次填写数据！");
								return bodyMap.modelMap;
							}
						}
					}
				}
			
		}
		try {
			/*if(!StringUtil.valitate(curAP.getBatch())&&!StringUtil.valitate(curAP.getId())){
				bodyMap.isFail();
				bodyMap.configWebInfor("入库的批次不能为空！");
				return bodyMap.modelMap;
			}else{
				if(curAP.getBillStatus()!=3){
					if(curAP.getBatch()!=null){
						curAP.setBatch("CO"+curAP.getBatch().replace("CO", ""));
					}
					SearchConditions scs = new SearchConditions();
					 if(StringUtil.valitate(curAP.getId())){
						 scs.addCondition("id",curAP.getId(),SearchCondition.OP_NOTEQUAL);
					 }
					 scs.addCondition("batch",curAP.getBatch(),SearchCondition.OP_EQUAL);
					 SearchResult sr= logicOtherInwhService.findListByExample(scs);
					 if(sr.getResults().size()>0){
							bodyMap.isFail();
							bodyMap.configWebInfor("您填写的批次号已存在请重新填写");
							return bodyMap.modelMap;
					}
				}
			}*/
			logicOtherInwhService.coSave(curAP, request);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		} catch (SyBaseException e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()
					+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap=BodyMsg.getInstance();
		try{
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicOtherInwhDO lot=logicOtherInwhService.findListById(field);
				if(lot.getId()!=null){
					lot.setRemoved(1);
					logicOtherInwhService.update(lot, SessionUtil.getUser(request));
				}
				//logicOtherInwhService.delete(field, SessionUtil.getUser(request));
			}
		
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed()+e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@RequestMapping(value = "/updateState")
	@ResponseBody
	public Map<String,String> updateState(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		Map<String,String> map=new HashMap<String,String>();
		try{
			String ids = request.getParameter("rows");
			if(ids!=null&&!"".equals(ids)){
				LogicOtherInwhDO lot=logicOtherInwhService.findListById(ids);
				if(lot.getId()!=null){
					lot.setBillStatus(Short.parseShort("1"));
					logicOtherInwhService.update(lot, SessionUtil.getUser(request));
					map.put("msg", "SUCCESS");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			map.put("msg", "ERROR");
		}
		return map;
	}
	
}
